import { IBreadCrumb } from '@/components/nav-header/src/c-cpns/types/types'
import { RouteRecordRaw } from 'vue-router'
let firstMenu: any = null
// 加载所有默认路由
export function mapAllRouter() {
  const allRoutes: RouteRecordRaw[] = []
  const routerFiles = require.context('@/router/main', true, /\.ts/)
  routerFiles.keys().forEach((key) => {
    const route = require('@/router/main' + key.split('.')[1])
    allRoutes.push(route.default)
  })
  return allRoutes
}

//根据服务器返回的菜单动态加载路由
export function mapMenuToRoutes(userMenus: RouteRecordRaw[]) {
  const allRoutes: RouteRecordRaw[] = mapAllRouter()
  const routes: RouteRecordRaw[] = []
  const _recurseGetRoutes = (menu: any[]) => {
    for (const item of menu) {
      if (allRoutes.find((route) => route.path === item.url)) {
        const route = allRoutes.find((route) => route.path === item.url)
        if (route) {
          routes.push(route)
        }

        if (!firstMenu) {
          firstMenu = item
        }
      } else {
        _recurseGetRoutes(item.children)
      }
    }
  }
  _recurseGetRoutes(userMenus)
  return routes
}

// 根据当前路径获取对应路由映射
export const pathMapToMenu = (
  userMenus: any[],
  currentPath: string,
  breadcrumbs?: IBreadCrumb[]
): any => {
  for (const item of userMenus) {
    if (item.children && item.children.length) {
      const findMenu = pathMapToMenu(item.children, currentPath)
      if (findMenu) {
        breadcrumbs?.push({ name: item.name })
        breadcrumbs?.push({ name: findMenu.name })
        return findMenu
      }
    } else if (item.url === currentPath) {
      return item
    }
  }
}

// 匹配面包屑导航
export const pathMapBreadcrumbs = (userMenus: any[], currentPath: string) => {
  const breadcrumbs: IBreadCrumb[] = []
  pathMapToMenu(userMenus, currentPath, breadcrumbs)
  return breadcrumbs
}
export { firstMenu }
